// pages/userinfo/userinfo.js
import ColorThief from '../../utils/color-thief.js'
import {
  rgbToHex,
  uuid,
  colorsEqual,
  saveBlendent
} from '../../utils/util.js'
const app = getApp()
const STATE_EMPTY = 0;
const STATE_LOADING = 1;
const STATE_SUCCEED = 2;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [{
        value: '男'
      },
      {
        value: '女',
        checked: 'true'
      },
    ],
    sex: '女',
    imgPath: null,
    imgInfo: {},
    colorCount: 5,
    state: STATE_EMPTY
  },
  name: function (res) {
    this.setData({
      name: res.detail.value
    })
  },
  radiochange: function (res) {
    console.log('picker发送选择改变，携带值为', res)
    this.setData({
      sex: res.detail.value
    })
  },
  sno: function (res) {
    this.setData({
      sno: res.detail.value
    })
  },
  grade: function (res) {
    this.setData({
      grade: res.detail.value
    })
  },
  contact: function (res) {
    this.setData({
      contact: res.detail.value
    })
  },

  xiugai: function (res) {
    const db = wx.cloud.database()
    db.collection("book_user")
      .where({
        _openid: getApp().globalData.openid
      })
      .get().then(res => {
        const userLen = res.data.length;
        //   if(userLen===0){
        //     const db = wx.cloud.database()
        //     db.collection("book_user")
        //       .add({
        //         data: {
        //           avatarurl:getApp().globalData.userInfo.avatarUrl,
        //           name: this.data.name,
        //           sex: this.data.sex,
        //           sno: this.data.sno,
        //           grade: this.data.grade,
        //           contact: this.data.contact,
        //         },
        //         success: function() {
        //           wx.showToast({
        //             title: '修改成功',
        //             duration: 2500
        //           })
        //         }
        //       })
        // } else 
        if (userLen === 1) {
          const db = wx.cloud.database()
          db.collection("book_user")
            .where({
              _openid: getApp().globalData.openid
            })
            .update({
              data: {
                imgPath: getApp().globalData.userInfo.avatarUrl,
                name: this.data.name,
                sex: this.data.sex,
                sno: this.data.sno,
                grade: this.data.grade,
                contact: this.data.contact,
                colors: this.data.colors,
                role: "读者",
              },
              success: function () {
                wx.switchTab({
                  url: '../mine/mine',
                  success: function () {
                    wx.showToast({
                      title: '修改成功',
                      duration: 2000
                    })
                  }
                })
              }
            })

        }
      })
  },

  //获取图片颜色
  chooseImg() {
    console.log('图片地址', this.data.imgPath)
    const that = this
    wx.getImageInfo({
      src: `${that.data.imgPath}`,
      success: (imgInfo) => {
        const poster = imgInfo.path
        console.log('3432', imgInfo.path)
        let {
          width,
          height,
          imgPath
        } = imgInfo;
        let scale = 0.8 * this.screenWidth / Math.max(width, height);
        let canvasWidth = Math.floor(scale * width);
        let canvasHeight = Math.floor(scale * height);
        this.setData({
          imgInfo,
          canvasScale: scale,
          canvasWidth,
          canvasHeight
        });
        let quality = 1;
        console.log(quality);
        this.colorThief.getPalette({
          width: canvasWidth,
          height: canvasHeight,
          imgPath: imgInfo.path,
          colorCount: this.data.colorCount,
          quality
        }, (colors) => {
          console.log('colors', colors);
          if (colors) {
            colors = colors.map((color) => {
              return ('#' + rgbToHex(color[0], color[1], color[2]))
            })
            this.setData({
              colors,
              state: STATE_SUCCEED
            })
            console.log('colors_16', this.data.colors)
          }
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const db = wx.cloud.database()
    db.collection("book_user")
      .where({
        _openid: getApp().globalData.openid
      })
      .get({
        success: res => {
          console.log(res.data[0]),
            this.setData({
              list: res.data[0],
              imgPath: getApp().globalData.userInfo.avatarUrl,
            })
          console.log('avatarUrl', this.data.imgPath)
          this.chooseImg()
          if (res.data[0].sex == "男") {
            this.setData({
              items: [{
                  value: '男',
                  checked: 'true'
                },
                {
                  value: '女'
                },
              ]
            })
          }
        },
        fail: err => {
          console.log(err)
        }
      })
    
    //获取图片颜色
    this.colorThief = new ColorThief('imageHandler');
    wx.getSystemInfo({
      success: ({
        screenWidth
      }) => {
        this.screenWidth = screenWidth;
      }
    })
    

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})